﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Relocation.Base;
using Relocation.Base.UI;
using Relocation.Com;
using Relocation.Com.Tools;
using Relocation.Data;
using Relocation.UI;


namespace Relocation.Controls
{
	/// <summary>
	/// 快速搜索用户控件
	/// </summary>
	public partial class MainTreeView : BaseControl
	{
		#region 变量声明
		/// <summary>
		/// 正在刷新
		/// </summary>
		public bool IsRefreshIng
		{
			get;
			private set;
		}

		private RelocateesWindow RelocateesWindow;

		public Relocatee[] ListRelocatee = null;

		/// <summary>
		/// 通过拆迁户的id，快速得到相关的安置人员
		/// </summary>
		public Dictionary<int, List<Placement>> DictionaryPlacements = new Dictionary<int, List<Placement>>();

		/// <summary>
		/// 通过拆迁户的id，快速得到相关的安置房
		/// </summary>
		public Dictionary<int, List<Relocatees_House>> DictionaryRelocateHouse = new Dictionary<int, List<Relocatees_House>>();

		/// <summary>
		/// 通过拆迁户id，快速得到户主
		/// </summary>
		public Dictionary<int, Placement> DictionaryHeadPlacment = new Dictionary<int, Placement>();

		#endregion


		public MainTreeView()
		{
			InitializeComponent();
		}

		public MainTreeView(Session session)
			: this()
		{
			this.Session = session;
		}

		/// <summary>
		/// 掉后台线程刷新整个树.
		/// </summary>
		public override void Refresh()
		{
			try
			{
				if (this.RelocateesWindow != null)
				{
					this.RelocateesWindow.Close();		// 关闭拆迁户窗体					
					if (!this.RelocateesWindow.IsDisposed)
					{
						//如果拆迁户窗体没正常关闭，则取消刷新
						this.Session.DataRefresh = false;
						return;
					}
				}
				GC.Collect();
				base.Refresh();
				if (!Session.DataRefresh || this.IsRefreshIng)
					return;
				this.IsRefreshIng = true;
				this.treeView.Nodes.Clear();

				WaitForm wait = new WaitForm("加载数据", "正在加载数据，请稍候...");
				ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj) {

					TreeNode node = CreateTreeNode(this.Session.Project);

					this.ExecInvoke(new MethodInvoker(delegate() {
						node.Expand();
						this.treeView.Nodes.Add(node);
						this.treeView.ContextMenuStrip = Session.User.IsGeneral() ? null : this.contextMenuTree;
						this.Session.DataRefresh = false;
						this.IsRefreshIng = false;
						wait.CloseForm();
					}));
				}));
				wait.ShowDialog();

			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				Log.Error(ex);
			}
		}

		#region 创建节点
		private TreeNode CreateTreeNode(Project project)
		{
			try
			{
				InitDictionary(this.Session.Project);		//初始化字典

				TimeSpan ts1 = new TimeSpan(System.DateTime.Now.Ticks);
				TreeNode nodeProject = new TreeNode();		//创建项目节点
				nodeProject = InitNodeProject(project, nodeProject);
				TreeNode[] villageNodes = GetVillageNodes();
				foreach (TreeNode villageNode in villageNodes)
				{
					string villageName = villageNode.Tag.ToString();
					TreeNode[] orgNodes = GetOrgNodes(villageName);
					foreach (TreeNode orgNode in orgNodes)
					{
						string orgName = orgNode.Tag.ToString();
						TreeNode[] relocateNodes = GetRelocateNodes(villageName, orgName);

						foreach (TreeNode relocateNode in relocateNodes)
						{
							Relocatee relocate = relocateNode.Tag as Relocatee;
							TreeNode[] placementNodes = GetPlacementNodes(relocate);
							TreeNode[] relocateHouseNodes = GetRelocateHouseNodes(relocate);
							relocateNode.Nodes.AddRange(placementNodes);
							relocateNode.Nodes.AddRange(relocateHouseNodes);
						}
						orgNode.Nodes.AddRange(relocateNodes);
					}
					villageNode.Nodes.AddRange(orgNodes);
					this.InitNodeVillageToolTipText(villageNode);	//一定要再将所有子节点添加完之后再执行此方法，
				}
				nodeProject.Nodes.AddRange(villageNodes);
				return nodeProject;
			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 返回村庄节点的数组
		/// </summary>		
		private TreeNode[] GetVillageNodes()
		{
			try
			{
				List<string> villages = this.ListRelocatee.Select(t => t.village).Distinct().ToList();
				villages.Sort();

				TreeNode[] nodes = new TreeNode[villages.Count];
				TreeNode nodeVillage = null;
				int count = 0;
				foreach (string village in villages)
				{
					nodeVillage = new TreeNode();
					nodeVillage = InitNodeVillage(village, nodeVillage);
					nodes[count++] = nodeVillage;
				}
				return nodes;
			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				throw;
			}
		}
		/// <summary>
		/// 返回单位节点的数组
		/// </summary>		
		private TreeNode[] GetOrgNodes(string villageName)
		{
			try
			{
				List<string> orgs = this.ListRelocatee.Where(t => (string.IsNullOrEmpty(villageName) ? string.IsNullOrEmpty(t.village) : villageName.Equals(t.village))).Select(t => t.organization).Distinct().ToList();
				orgs.Sort();
				TreeNode[] nodes = new TreeNode[orgs.Count];
				TreeNode nodeOrg = null;
				int count = 0;
				foreach (string org in orgs)
				{
					nodeOrg = new TreeNode();
					nodeOrg = InitNodeOrganization(org, nodeOrg);
					nodes[count++] = nodeOrg;
				}
				return nodes;
			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 返回拆迁户节点的数组
		/// </summary>		
		private TreeNode[] GetRelocateNodes(string villageName, string orgName)
		{
			try
			{
				bool villageNameIsNull = string.IsNullOrEmpty(villageName);
				bool orgNameIsNull = string.IsNullOrEmpty(orgName);
				List<Relocatee> relocatees = this.ListRelocatee.Where(t => (villageNameIsNull ? string.IsNullOrEmpty(t.village) : villageName.Equals(t.village)) && (orgNameIsNull ? string.IsNullOrEmpty(t.organization) : orgName.Equals(t.organization))).OrderBy(t => t.head).ToList();
				TreeNode[] nodes = new TreeNode[relocatees.Count];
				TreeNode nodeRelocate = null;
				int count = 0;
				foreach (Relocatee relocatee in relocatees)
				{
					nodeRelocate = new TreeNode();
					nodeRelocate = InitNodeRelocate(relocatee, nodeRelocate, true);
					nodes[count++] = nodeRelocate;
				}
				return nodes;
			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 返回安置人员节点的数组
		/// </summary>			
		private TreeNode[] GetPlacementNodes(Relocatee relocatee)
		{
			try
			{
				List<Placement> list = this.DictionaryPlacements[relocatee.relocatees_id];
				TimeSpan ts2 = new TimeSpan(System.DateTime.Now.Ticks);
				TreeNode[] nodes = new TreeNode[list.Count];
				TreeNode node = null;
				int count = 0;
				foreach (var item in list)
				{
					node = new TreeNode();
					node = InitNodePlacement(item, node);
					nodes[count++] = node;
				}
				return nodes;
			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 返回安置房节点的数组
		/// </summary>		
		private TreeNode[] GetRelocateHouseNodes(Relocatee relocatee)
		{
			try
			{
				List<Relocatees_House> list = this.DictionaryRelocateHouse[relocatee.relocatees_id];
				TreeNode[] nodes = new TreeNode[list.Count];
				TreeNode node = null;
				int count = 0;
				foreach (var item in list)
				{
					node = new TreeNode();
					node = InitNodeRelocateesHouse(item, node);
					nodes[count++] = node;
				}
				return nodes;
			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				throw;
			}
		}
		#endregion


		/// <summary>
		/// 初始化数据
		/// </summary>
		/// <param name="tempProject"></param>
		private void InitDictionary(Project project)
		{
			try
			{

				this.ListRelocatee = project.Relocatees.CreateSourceQuery().ToArray();
				this.DictionaryHeadPlacment.Clear();
				this.DictionaryPlacements.Clear();
				this.DictionaryRelocateHouse.Clear();

				Placement[] ListPlacement = this.Session.DataModel.Placements.Where(t => t.Relocatee.Project.project_id == project.project_id).ToArray();
				Relocatees_House[] ListRelicateHouse = this.Session.DataModel.Relocatees_House.Where(t => t.Relocatee.Project.project_id == project.project_id).ToArray();

				foreach (var relocatee in ListRelocatee)
				{
					this.DictionaryPlacements[relocatee.relocatees_id] = new List<Placement>();
					this.DictionaryRelocateHouse[relocatee.relocatees_id] = new List<Relocatees_House>();
				}
				string errString = "";
				foreach (var placement in ListPlacement)
				{

					if (placement.IsHead())
					{
						if (this.DictionaryHeadPlacment.ContainsKey(placement.Relocatee.relocatees_id))
						{
							errString = string.Format("拆迁户【{0}】（id为：{1}）有多个户主，人员名称：{2}", placement.Relocatee.head, placement.Relocatee.relocatees_id, placement.name);
							Log.Error(errString);
							Debug.WriteLine(errString);
							continue;
						}
						this.DictionaryHeadPlacment.Add(placement.Relocatee.relocatees_id, placement);
						continue;
					}
					this.DictionaryPlacements[placement.Relocatee.relocatees_id].Add(placement);
				}
				foreach (var relocateHouse in ListRelicateHouse)
				{
					this.DictionaryRelocateHouse[relocateHouse.Relocatee.relocatees_id].Add(relocateHouse);
				}
			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				throw;
			}
		}



		#region 刷新修改的节点
		/// <summary>
		/// 刷新树中被修改的节点.
		/// </summary>		
		public void RefreshNode<TEntity>(TEntity entity, EntityState entityState)
			where TEntity : System.Data.Objects.DataClasses.EntityObject
		{
			switch (entity.GetType().Name)
			{
				case "Relocatee":
					RefreshNode(entity as Relocatee, entityState);
					break;
				case "Placement":
					RefreshNode(entity as Placement, entityState);
					break;
				case "Relocatees_House":
					RefreshNode(entity as Relocatees_House, entityState);
					break;
				case "Project":
					RefreshNode(entity as Project, entityState);
					break;
			}
		}

		/// <summary>
		/// 刷新树中被修改的项目.
		/// </summary>		
		private void RefreshNode(Project entity, EntityState entityState)
		{
			TreeNode entityNode = FindNode(entity);
			if (entityNode == null)
			{
				Log.Error("未找到需要更新的项目。");
				return;
			}
			this.InitNodeProject(entity, entityNode);
		}

		/// <summary>
		/// 刷新树中被修改的村庄（单位）
		/// </summary>		
		private void RefreshNode(TreeNode villageNode)
		{
			int allhouse = 0;
			int nohouse = 0;
			int housing = 0;
			int housed = 0;

			foreach (TreeNode organizationNode in villageNode.Nodes)
			{
				int allhouse2 = 0;
				int nohouse2 = 0;
				int housing2 = 0;
				int housed2 = 0;

				foreach (TreeNode relocateesNode in organizationNode.Nodes)
				{
					Relocatee relocatees = (Relocatee)relocateesNode.Tag;

					this.ExecInvoke(new MethodInvoker(delegate() {
						//根据安置户的安置状态修改背景色和图标
						setRelocatImageKey(relocateesNode, relocatees);

					}));

					switch (relocatees.status)
					{
						case 1:
							housing++;
							housing2++;
							break;
						case 2:
							housed++;
							housed2++;
							break;
						default:
							nohouse++;
							nohouse2++;
							break;
					}
					allhouse++;
					allhouse2++;
				}
				this.ExecInvoke(new MethodInvoker(delegate() {
					organizationNode.ImageKey = "Field_Organization";
					organizationNode.ToolTipText = "总户数：" + allhouse2 + "户,其中 已安置：" + housed2 + "户、未安置：" + nohouse2 + "户、安置中：" + housing2 + "户";
				}));


			}
			this.ExecInvoke(new MethodInvoker(delegate() {
				villageNode.ImageKey = "Village";
				villageNode.ToolTipText = "总户数：" + allhouse + "户,其中 已安置：" + housed + "户、未安置：" + nohouse + "户、安置中：" + housing + "户";
			}));

		}

		/// <summary>
		/// 刷新树中被修改的拆迁户.
		/// </summary>		
		private void RefreshNode(Relocatee relocate, EntityState entityState)
		{
			try
			{
				switch (entityState)
				{
					case EntityState.Deleted:
						TreeNode relocateNode = FindNode(relocate);
						if (relocateNode == null)
						{
							Log.Error("拆迁户节点未找到！");
							Debug.WriteLine("拆迁户节点未找到！");
							return;
						}
						TreeNode pnodeOrg = relocateNode.Parent;
						TreeNode pnodeVillage = pnodeOrg == null ? null : pnodeOrg.Parent;

						relocateNode.Remove();
						if (pnodeOrg != null && pnodeOrg.GetNodeCount(true) == 0)
							pnodeOrg.Remove();
						if (pnodeVillage != null && pnodeVillage.GetNodeCount(true) == 0)
							pnodeVillage.Remove();
						else
							this.InitNodeVillageToolTipText(pnodeVillage);
						break;
					case EntityState.Modified:
					case EntityState.Detached:
					case EntityState.Added:
						TreeNode node2 = RefreshRelocateNode(relocate);
						ShowNode(node2);
						this.InitNodeVillageToolTipText(node2.Parent.Parent);
						break;
				}
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		private TreeNode RefreshRelocateNode(Relocatee relocate)
		{
			try
			{
				TreeNode relocateNode = FindNode(relocate);
				string organizationName = relocate.organization == null ? string.Empty : relocate.organization;
				string villageName = relocate.village == null ? string.Empty : relocate.village;
				if (relocateNode == null)
				{
					relocateNode = new TreeNode();
				}
				this.InitNodeRelocate(relocate, relocateNode);
				TreeNode porjectNode = this.FindNode(this.Session.Project);
				TreeNode tagPNodeVillage = this.FindNodeByTagString(relocate.village, porjectNode);
				TreeNode tagPNodeOrg = tagPNodeVillage == null ? null : this.FindNodeByTagString(relocate.organization, tagPNodeVillage);

				if (tagPNodeVillage == null)
				{
					tagPNodeVillage = new TreeNode();
					tagPNodeVillage = InitNodeVillage(relocate.village, tagPNodeVillage);
					porjectNode.Nodes.Add(tagPNodeVillage);
				}
				if (tagPNodeOrg == null)
				{
					tagPNodeOrg = new TreeNode();
					tagPNodeOrg = InitNodeOrganization(relocate.organization, tagPNodeOrg);
					tagPNodeVillage.Nodes.Add(tagPNodeOrg);
				}

				TreeNode pnode1 = relocateNode.Parent;
				TreeNode pnode2 = pnode1 == null ? null : pnode1.Parent;
				if (pnode1 != tagPNodeOrg)
				{
					relocateNode.Remove();
					tagPNodeOrg.Nodes.Add(relocateNode);
					if (pnode1 != null && pnode1.Nodes.Count < 1)
						pnode1.Remove();
					if (pnode2 != null && pnode2.Nodes.Count < 1)
						pnode2.Remove();
					//if (tagPNodeOrg.Parent != tagPNodeVillage)
					//{
					//        tagPNodeVillage.Nodes.Add(tagPNodeOrg);

					//}
				}
				this.InitNodeVillageToolTipText(tagPNodeVillage);
				return relocateNode;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 刷新树中被修改的安置人员.
		/// </summary>		
		private void RefreshNode(Placement entity, EntityState entityState)
		{
			try
			{
				Relocatee relocatee = entity.GetRelocatee();
				TreeNode relocateNode = FindNode(relocatee);
				if (entity.relation == "户主")
				{
					if (entityState == EntityState.Added | entityState == EntityState.Detached)
					{
						this.InitNodeRelocate(relocatee, relocateNode);
					}
				} else
				{
					TreeNode placementNode = FindNode(entity);
					switch (entityState)
					{
						case EntityState.Deleted:
							if (placementNode == null)
							{
								Log.Error("安置人员节点未找到！");
							} else
							{
								placementNode.Remove();
							}
							break;
						case EntityState.Modified:

						case EntityState.Detached:
						case EntityState.Added:
							if (placementNode == null)
							{
								placementNode = new TreeNode();
								relocateNode.Nodes.Add(placementNode);
							}
							this.InitNodePlacement(entity, placementNode);
							ShowNode(placementNode);
							break;
					}
				}
				this.InitNodeVillageToolTipText(relocateNode.Parent.Parent);
			} catch (Exception ex)
			{
				Log.Error(ex);
				Debug.WriteLine(ex);
			}

		}

		/// <summary>
		/// 刷新树中被修改的安置房.
		/// </summary>
		/// <param name="tagEntity">The tagEntity.</param>
		private void RefreshNode(Relocatees_House entity, EntityState entityState)
		{
			try
			{
				TreeNode entityNode = FindNode(entity);
				switch (entityState)
				{
					case EntityState.Deleted:
						if (entityNode == null)
						{
							Log.Error("删除安置房时未找到节点");
							return;
						}
						entityNode.Remove();
						break;
					case EntityState.Modified:
					case EntityState.Detached:
					case EntityState.Added:
						if (entityNode == null)
						{
							entityNode = new TreeNode();
							TreeNode relocateNode = this.FindNode(entity.GetRelocate());
							relocateNode.Nodes.Add(entityNode);
						}
						entityNode = InitNodeRelocateesHouse(entity, entityNode);
						ShowNode(entityNode);
						break;
				}
				this.InitNodeVillageToolTipText(entityNode.Parent.Parent.Parent);
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}
		#endregion


		#region 查找树形节点

		/// <summary>
		/// 查找实体节点.
		/// </summary>		
		public TreeNode FindNode<TEntity>(TEntity entity)
			where TEntity : System.Data.Objects.DataClasses.EntityObject
		{
			if (entity is Relocatee)
			{
				return FindNode(entity as Relocatee);
			} else if (entity is Placement)
			{
				return FindNode(entity as Placement);
			} else if (entity is Relocatees_House)
			{
				return FindNode(entity as Relocatees_House);
			} else if (entity is Project)
			{
				return FindNode(entity as Project);
			} else
				return null;

		}


		/// <summary>
		/// 查找【项目】节点.
		/// </summary>		
		private TreeNode FindNode(Project projectEntity)
		{
			if (projectEntity == null)
				return null;
			Project tempProject = null;
			foreach (TreeNode projectNode in this.treeView.Nodes)
			{
				tempProject = projectNode.Tag as Project;
				if (tempProject != null && projectEntity.project_id.Equals(tempProject.project_id))
					return projectNode;
			}
			return null;
		}

		/// <summary>
		/// 查找【村庄】节点
		/// </summary>		
		private TreeNode FindNodeVillage(string villageName)
		{
			villageName = string.IsNullOrEmpty(villageName) ? string.Empty : villageName;
			foreach (TreeNode node_Project in this.treeView.Nodes)
			{
				foreach (TreeNode nodeVillage in node_Project.Nodes)
				{
					if (villageName.EqualsNullable(nodeVillage.Tag.ToString()))
						return nodeVillage;
				}
			}
			return null;
		}

		/// <summary>
		/// 查找【单位】节点
		/// </summary>		
		private TreeNode FindNodeOrg(string villageName, string orgName)
		{
			orgName = string.IsNullOrEmpty(orgName) ? string.Empty : orgName;
			TreeNode nodeVillage = this.FindNodeVillage(villageName);
			if (nodeVillage == null)
				return null;
			foreach (TreeNode nodeOrg in nodeVillage.Nodes)
			{
				if (orgName.EqualsNullable(nodeOrg.Tag.ToString()))
					return nodeOrg;
			}
			return null;
		}

		/// <summary>
		/// 查找【拆迁户】节点.
		/// </summary>		
		private TreeNode FindNode(Relocatee entity)
		{
			if (entity == null)
				return null;
			Relocatee relocatee = null;
			//TreeNode nodeOrg = this.FindNodeOrg(entity.village, entity.organization);
			//if (nodeOrg == null)
			//        return null;

			//foreach (TreeNode node_Relocatee in nodeOrg.Nodes)
			//{
			//        relocatee = node_Relocatee.Tag as Relocatee;
			//        if (relocatee != null && entity.relocatees_id.Equals(relocatee.relocatees_id))
			//                return node_Relocatee;
			//}
			if (relocatee == null)
			{
				foreach (TreeNode nodePro in this.treeView.Nodes)
				{
					foreach (TreeNode node_Village in nodePro.Nodes)
					{
						foreach (TreeNode node_Org in node_Village.Nodes)
						{
							foreach (TreeNode node_relocatee in node_Org.Nodes)
							{
								if (node_relocatee.Tag != null)
								{
									relocatee = node_relocatee.Tag as Relocatee;
									if (relocatee != null && entity.relocatees_id.Equals(relocatee.relocatees_id))
										return node_relocatee;
								}

							}
						}
					}
				}
			}
			return null;
		}

		/// <summary>
		/// 查找【安置人员】节点.
		/// </summary>		
		private TreeNode FindNode(Placement entity)
		{
			if (entity.relation == "户主")
			{
				return null;	//户主没有节点
			}


			TreeNode relocateNode = FindNode(entity.GetRelocatee());	//先查找拆迁户节点 


			if (relocateNode == null)
				return null;
			Placement placement = null;
			foreach (TreeNode node in relocateNode.Nodes)
			{
				if (node.Tag != null)
				{
					placement = node.Tag as Placement;
					if (placement != null && placement.placement_id == entity.placement_id)
					{
						return node;
					}
				}
			}
			return null;
		}

		/// <summary>
		/// 查找【安置房】节点.
		/// </summary>		
		private TreeNode FindNode(Relocatees_House entity)
		{
			TreeNode relocateNode = FindNode(entity.GetRelocate());	//先查找拆迁户节点
			if (relocateNode == null)
				return null;
			Relocatees_House RelocateHouse = null;
			foreach (TreeNode node in relocateNode.Nodes)
			{
				if (node.Tag != null)
				{
					RelocateHouse = node.Tag as Relocatees_House;
					if (RelocateHouse != null && RelocateHouse.relocatees_house_id == entity.relocatees_house_id)
					{
						return node;
					}
				}
			}
			return null;
		}

		private TreeNode FindNodeByTagString(string tagString, TreeNode node)
		{
			if (node == null)
				return null;
			tagString = string.IsNullOrEmpty(tagString) ? string.Empty : tagString;
			string tag = null;
			foreach (TreeNode _node in node.Nodes)
			{
				tag = _node.Tag == null ? string.Empty : _node.Tag.ToString();
				if (tagString.EqualsNullable(tag))
					return _node;
			}
			return null;

		}

		#endregion


		#region 通过对象初始化TreeNode

		/// <summary>
		/// 设置Projects对应的TreeNode
		/// </summary>		
		private TreeNode InitNodeProject(Project entity, TreeNode node)
		{
			try
			{
				if (entity == null || node == null)
					return node;
				node.Text = entity.GetNodeText();
				node.Tag = entity;
				node.ImageKey = entity.GetImageKey();
				node.ToolTipText = entity.GetNodeToolTipText();
				node.ContextMenuStrip = Session.User.IsGeneral() ? null : this.contextMenuProject;
				return node;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 创建Relocatees对应的TreeNode
		/// </summary>
		/// <param name="relocatees">拆迁户</param>
		/// <param name="node">拆迁户节点</param>
		/// <param name="isTreeViewRefresh">来自树形控件的刷新</param>
		/// <returns></returns>
		private TreeNode InitNodeRelocate(Relocatee relocatees, TreeNode node, bool isTreeViewRefresh)
		{
			try
			{
				string idNumber = string.Empty;
				if (isTreeViewRefresh)
				{
					if (this.DictionaryHeadPlacment.ContainsKey(relocatees.relocatees_id))
					{
						idNumber = this.DictionaryHeadPlacment[relocatees.relocatees_id].id_number;
					}
				} else
				{
					idNumber = relocatees.Placements.CreateSourceQuery().Where(it => "户主".Equals(it.relation)).Select(it => it.id_number).FirstOrDefault();
				}

				node.Text = relocatees.head + (string.IsNullOrEmpty(idNumber) ? string.Empty : ("（" + idNumber + "）"));
				node.Tag = relocatees;
				node.ToolTipText = relocatees.GetNodeToolTipText();
				node.ImageKey = relocatees.GetImageKey();
				node.BackColor = relocatees.GetNodeBackColor();
				if (relocatees.IsNotCompleted)
					node.ForeColor = Color.Red;
				node.ContextMenuStrip = Session.User.IsGeneral() ? null : this.contextMenuRelocation;
				return node;
			} catch (Exception ex)
			{
				Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 创建Relocatees对应的TreeNode
		/// </summary>	
		private TreeNode InitNodeRelocate(Relocatee relocatees, TreeNode node)
		{
			return InitNodeRelocate(relocatees, node, false);
		}

		/// <summary>
		/// 创建village对应的TreeNode
		/// </summary>		
		private TreeNode InitNodeVillage(string entityName, TreeNode node)
		{
			entityName = entityName == null ? string.Empty : entityName;
			node.Text = entityName;
			node.Tag = entityName;
			node.ImageKey = "Village";
			this.InitNodeVillageToolTipText(node);
			node.ContextMenuStrip = Session.User.IsGeneral() ? null : this.contextMenuTree;
			return node;
		}

		/// <summary>
		/// 设置村庄节点及单位节点的ToolTipText
		/// </summary>
		private TreeNode InitNodeVillageToolTipText(TreeNode node)
		{
			if (node == null)
				return null;
			try
			{
				int allhouse = 0;
				int nohouse = 0;
				int housing = 0;
				int housed = 0;
				foreach (TreeNode organizationNode in node.Nodes)
				{
					int allhouse2 = 0;
					int nohouse2 = 0;
					int housing2 = 0;
					int housed2 = 0;
					foreach (TreeNode relocateesNode in organizationNode.Nodes)
					{
						Relocatee relocatees = relocateesNode.Tag as Relocatee;

						switch (relocatees.status)
						{
							case 1:
								housing++;
								housing2++;
								break;
							case 2:
								housed++;
								housed2++;
								break;
							default:
								nohouse++;
								nohouse2++;
								break;
						}
						allhouse++;
						allhouse2++;
					}
					this.ExecInvoke(new MethodInvoker(delegate() {
						organizationNode.ToolTipText = "总户数：" + allhouse2 + "户,其中 已安置：" + housed2 + "户、未安置：" + nohouse2 + "户、安置中：" + housing2 + "户";
					}));
				}
				this.ExecInvoke(new MethodInvoker(delegate() {
					node.ToolTipText = "总户数：" + allhouse + "户,其中 已安置：" + housed + "户、未安置：" + nohouse + "户、安置中：" + housing + "户";
				}));
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
			}
			return node;

		}
		/// <summary>
		/// 设置organization对应的TreeNode
		/// </summary>		
		private TreeNode InitNodeOrganization(string entityName, TreeNode node)
		{
			try
			{
				entityName = entityName == null ? string.Empty : entityName;
				node.Text = string.IsNullOrEmpty(entityName) ? "（无单位）" : entityName;
				node.Tag = entityName;
				node.ImageKey = "Field_Organization";
				node.ContextMenuStrip = Session.User.IsGeneral() ? null : this.contextMenuTree;
				return node;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 设置Relocatees_House对应的TreeNode
		/// </summary>		
		private TreeNode InitNodeRelocateesHouse(Relocatees_House entity, TreeNode node)
		{
			try
			{
				if (entity == null || node == null)
					return node;
				node.Text = entity.GetNodeText();
				node.Tag = entity;
				node.ImageKey = entity.GetImageKey();
				node.ToolTipText = entity.GetNodeToolTipText();
				node.ContextMenuStrip = Session.User.IsGeneral() ? null : this.contextMenuHouse;
				return node;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// 设置Placement对应的TreeNode
		/// </summary>		
		private TreeNode InitNodePlacement(Placement entity, TreeNode node)
		{
			try
			{
				if (entity == null || node == null)
					return node;
				node.Tag = entity;
				node.Text = entity.GetNodeText();
				node.ImageKey = entity.GetImageKey();
				node.ToolTipText = entity.GetNodeToolTipText();
				node.ContextMenuStrip = Session.User.IsGeneral() ? null : this.contextMenuPlacement;
				return node;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		#endregion

		/// <summary>
		/// 显示、并选中节点
		/// </summary>
		private void ShowNode(TreeNode node)
		{
			node.EnsureVisible();
			this.treeView.SelectedNode = node;
		}



		#region 事件相关方法

		/// <summary>
		/// Handles the Click event of the buttonSearch control.
		/// </summary>		
		private void buttonSearch_Click(object sender, EventArgs e)
		{
			try
			{
				this.toolStripSearchString.Text = this.toolStripSearchString.Text.Trim();
				if (this.toolStripSearchString.Text == "")
					return;
				TreeNode node = searchNode(this.treeView.Nodes, this.toolStripSearchString.Text);
				if (node != null)
				{
					this.treeView.Focus();
					ShowNode(node);
				} else
					MyMessagebox.Show("未找到符合要求的数据！");
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("搜索数据时发生错误！");
			}
		}

		private void toolStripFindNext_Click(object sender, EventArgs e)
		{
			try
			{
				this.toolStripSearchString.Text = this.toolStripSearchString.Text.Trim();
				if (this.toolStripSearchString.Text == "")
					return;
				TreeNode node = (this.treeView.SelectedNode == null) ? searchNode(this.treeView.Nodes, this.toolStripSearchString.Text)
					: searchNextNode(this.treeView.SelectedNode, this.toolStripSearchString.Text);
				if (node != null)
				{
					this.treeView.Focus();
					ShowNode(node);
				} else
					MyMessagebox.Show("未找到符合要求的数据！");
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("搜索数据时发生错误！");
			}
		}

		private TreeNode searchNode(TreeNodeCollection nodes, string searchString)
		{
			try
			{
				if (nodes.Count == 0)
					return null;
				foreach (TreeNode node in nodes)
				{
					if (node.Level > 0 && node.Text.Contains(searchString))
					{

						return node;
					} else
					{
						TreeNode childNode = searchNode(node.Nodes, searchString);
						if (childNode != null)
							return childNode;
					}
				}
				return null;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// Searches the next nodeProject.
		/// </summary>
		/// <param name="nodeProject">The nodeProject.</param>
		/// <param name="searchString">The search string.</param>
		/// <returns></returns>
		private TreeNode searchNextNode(TreeNode currentNode, string searchString)
		{
			try
			{
				TreeNode node = searchNode(currentNode.Nodes, searchString);
				if (node != null)
					return node;
				TreeNode nextNode = currentNode.NextNode;
				if (nextNode == null)
				{
					TreeNode pnode = currentNode.Parent;
					while (pnode != null && pnode.NextNode == null)
						pnode = pnode.Parent;
					if (pnode == null)
						return null;
					if (pnode.NextNode.Text.Contains(searchString))
						return pnode.NextNode;
					return searchNextNode(pnode.NextNode, searchString);
				} else if (nextNode.Text.Contains(searchString))
					return nextNode;
				else
					return searchNextNode(nextNode, searchString);
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		/// <summary>
		/// Shows the form.
		/// </summary>
		/// <param name="form">The form.</param>
		private void showForm(Form form)
		{
			try
			{
				foreach (Form oldForm in this.splitContainer.Panel2.Controls)
				{
					oldForm.Close();
				}
				form.FormBorderStyle = FormBorderStyle.None;
				form.Dock = DockStyle.Fill;
				form.TopLevel = false;
				form.Parent = this.splitContainer.Panel2;
				//Main frmMain = new Main();
				form.Show();
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}

		}

		/// <summary>
		/// Handles the AfterSelect event of the treeView control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param>
		private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
		{
			try
			{
				TreeNode currentNode = e.Node;
				Relocatee relocatees;
				if (currentNode.Level == 3)
				{
					relocatees = currentNode.Tag as Relocatee;
				} else if (currentNode.Level == 4)
				{
					relocatees = currentNode.Parent.Tag as Relocatee;
				} else
					return;
				EntityObject eneity = currentNode.Tag as EntityObject;
				if (RelocateesWindow == null || RelocateesWindow.IsDisposed)
				{
					RelocateesWindow = new RelocateesWindow(this.Session, relocatees);

					RelocateesWindow.FormBorderStyle = FormBorderStyle.None;
					RelocateesWindow.Dock = DockStyle.Fill;
					RelocateesWindow.TopLevel = false;
					RelocateesWindow.Parent = this.splitContainer.Panel2;
					RelocateesWindow.Show();
					RelocateesWindow.LoadEntity(eneity);	//需要将这个方法放在Show方法后面
				} else
				{
					RelocateesWindow.LoadEntity(relocatees, eneity);
				}


			} catch (Exception ex)
			{
				Log.Error(Tools.GetExceptionMessage(ex));
				MyMessagebox.Error(ex);
			}
		}

		/// <summary>
		/// Handles the Click event of the buttonExpandAll control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void buttonExpandAll_Click(object sender, EventArgs e)
		{
			this.treeView.ExpandAll();
		}

		/// <summary>
		/// Handles the Click event of the buttonCollapseAll control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void buttonCollapseAll_Click(object sender, EventArgs e)
		{
			this.treeView.CollapseAll();
		}

		/// <summary>
		/// Handles the Click event of the buttonRefresh control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void buttonRefresh_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.IsRefreshIng)
				{
					MyMessagebox.Show("菜单正在刷新，请稍候...");
					return;
				}
				this.Session.DataRefresh = true;
				this.Refresh();
				if (this.RelocateesWindow != null)
					this.RelocateesWindow.Refresh();
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("刷新菜单时发生错误！");
			}

		}

		/// <summary>
		/// Handles the KeyPress event of the textSearchString control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.Windows.Forms.KeyPressEventArgs"/> instance containing the event data.</param>
		private void textSearchString_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == '\r')
				buttonSearch_Click(sender, e);
		}

		/// <summary>
		/// Handles the Enter event of the MainTreeView control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void MainTreeView_Enter(object sender, EventArgs e)
		{
			this.toolStripSearchString.Focus();
		}

		private void toolStripRelocation_Click(object sender, EventArgs e)
		{
			this.ShowNewRelocateDialog();
		}

		/// <summary>		
		/// 新增拆迁户
		/// </summary>
		private void menuItemAddRelocation_Click(object sender, EventArgs e)
		{

			try
			{
				TreeNode selectedNode = (TreeNode)((ToolStripMenuItem)sender).Owner.Tag;
				string villagName = string.Empty;
				string orgName = string.Empty;
				if (selectedNode != null && selectedNode.Level != 0)
				{
					if (selectedNode.Level.Equals(1))
					{
						villagName = selectedNode.Tag == null ? string.Empty : selectedNode.Tag.ToString();

					} else if (selectedNode.Level.Equals(2))
					{
						villagName = (selectedNode.Parent == null || selectedNode.Parent.Tag == null) ? string.Empty : selectedNode.Parent.Tag.ToString();
						orgName = selectedNode.Tag == null ? string.Empty : selectedNode.Tag.ToString();
					}
				}

				ShowNewRelocateDialog(villagName, orgName);
			} catch (Exception ex)
			{
				Log.Error(ex);
				MyMessagebox.Show("操作失败！");
			}
		}

		private DialogResult ShowNewRelocateDialog(string villageName = "", string orgName = "")
		{
			using (RelocateesWindow relocateesWindow = new RelocateesWindow(this.Session))
			{
				relocateesWindow.Field_Village.Text = villageName;
				relocateesWindow.Field_Organization.Text = orgName;
				relocateesWindow.FieldIsChanged = false;
				relocateesWindow.MaximizeBox = false;
				relocateesWindow.MinimizeBox = false;
				relocateesWindow.MaximumSize = new System.Drawing.Size(800, 430);
				relocateesWindow.MinimumSize = new System.Drawing.Size(800, 430);
				return relocateesWindow.ShowDialog();
			}
		}

		/// <summary>
		/// 修改拆迁户
		/// </summary>
		private void menuItemEditRelocatees_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.RelocateesWindow != null)
					this.RelocateesWindow.BeginEdit();
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("操作失败！");
			}
		}

		/// <summary>		
		/// 新增安置人员
		/// </summary>		
		private void menuItemAddPlacement_Click(object sender, EventArgs e)
		{

			try
			{
				TreeNode selectedNode = (TreeNode)((ToolStripMenuItem)sender).Owner.Tag;
				Relocatee relocatees = selectedNode.Tag as Relocatee;
				if (relocatees == null)
					return;
				PlacementWindow window = new PlacementWindow(this.Session, relocatees);
				if (window.ShowDialog(this).Equals(DialogResult.OK))
				{

					if (this.RelocateesWindow == null)
						return;
					this.RelocateesWindow.Refresh();
				}
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("操作失败！");
			}
		}

		/// <summary>		
		/// 分配安置房
		/// </summary>		
		private void menuItemHouse_Click(object sender, EventArgs e)
		{
			try
			{
				//Relocatee relocatees = this.GetTagObjByEventSender<Relocatee>(sender);
				this.RelocateesWindow.GetRelocateesHouseList().addItem_Click(null, null);
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Error("分配安置房时发生错误！");
			}

		}

		private T GetTagObjByEventSender<T>(object sender)
			where T : class
		{
			TreeNode selectedNode = (TreeNode)((ToolStripMenuItem)sender).Owner.Tag;
			return selectedNode.Tag as T;
		}

		/// <summary>		
		/// 取消安置房分配
		/// </summary>
		private void menuItemDelHouse_Click(object sender, EventArgs e)
		{
			try
			{
				this.RelocateesWindow.GetRelocateesHouseList().DeleteButton_Click(null, null);
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Error("取消安置房分配时发生错误！");
			}
		}

		/// <summary>		
		/// 删除安置人员
		/// </summary>		
		private void menuItemDelPlacement_Click(object sender, EventArgs e)
		{
			try
			{
				this.RelocateesWindow.GetPlacementList().ButtonDel_Click(null, null);
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Error("删除安置人员时发生错误！");
			}
		}

		public void deleteRelocatees(TreeNode relocateesNode)
		{
			if (MyMessagebox.Confirm("您确定要删除拆迁户及其相关的安置人员和安置房吗？").IsYes())
			{
				this.Session.DataModel.Connection.Open();
				TreeNode selectedNode = relocateesNode;
				System.Data.Common.DbTransaction transaction = this.Session.DataModel.Connection.BeginTransaction();
				try
				{
					Relocatee relocatees = (Relocatee)selectedNode.Tag;
					relocatees.ProjectReference.Load();

					this.Session.DataModel.Refresh(System.Data.Objects.RefreshMode.ClientWins, relocatees);

					this.Session.DataModel.Refresh(System.Data.Objects.RefreshMode.ClientWins, relocatees.Placements);

					while (relocatees.Placements.Count > 0)
						this.Session.DataModel.Delete(relocatees.Placements.First());

					while (relocatees.Relocatees_House.Count > 0)
						this.Session.DataModel.Delete(relocatees.Relocatees_House.First());

					this.Session.DataModel.Delete(relocatees);
					transaction.Commit();
				} catch (Exception ex)
				{
					Log.Error(ex.Message);
					transaction.Rollback();
					this.Session.DataModel.Connection.Close();
					MyMessagebox.Error(ex.Message);
					return;
				}
				this.Session.DataModel.Connection.Close();

				TreeNode pnode1 = selectedNode.Parent;
				TreeNode pnode2 = selectedNode.Parent.Parent;

				selectedNode.Remove();

				if (pnode1.Nodes.Count == 0)
					pnode1.Remove();
				if (pnode2.Nodes.Count == 0)
					pnode2.Remove();
				else
					this.RefreshNode(pnode2);
				if (this.splitContainer.Panel2.Controls.Count > 0)
				{
					this.RelocateesWindow.Close();
					this.RelocateesWindow = null;
				}
			}
		}

		/// <summary>		
		/// 删除拆迁户
		/// </summary>		
		private void menuItemDelRelocatees_Click(object sender, EventArgs e)
		{
			deleteRelocatees((TreeNode)((ToolStripMenuItem)sender).Owner.Tag);
		}

		/// <summary>
		/// Handles the Click event of the menuItemSelectProject control.
		/// </summary>		
		private void menuItemSelectProject_Click(object sender, EventArgs e)
		{
			MainWindow mainWin = (MainWindow)this.FindForm();
			mainWin.ProChoose_ToolStripMenuItem_Click(sender, e);
		}

		/// <summary>
		/// Handles the Click event of the menuItemVisible control.
		/// </summary>		
		private void menuItemVisible_Click(object sender, EventArgs e)
		{
			this.splitContainer.Panel1Collapsed = true;
			this.splitContainer.ContextMenuStrip = contextMenuNavigate;
		}

		/// <summary>
		/// Handles the Click event of the menuItemNavigate control.
		/// </summary>		
		private void menuItemNavigate_Click(object sender, EventArgs e)
		{
			this.splitContainer.Panel1Collapsed = false;
			this.splitContainer.ContextMenuStrip = null;
		}

		/// <summary>
		/// 修改项目
		/// </summary>		
		private void MenuItemAlterProject_Click(object sender, EventArgs e)
		{
			try
			{
				TreeNode selectedNode = (TreeNode)((ToolStripMenuItem)sender).Owner.Tag;
				Project project = selectedNode.Tag as Project;
				ProjectsWindow projectWindow = new ProjectsWindow(Session, project);
				projectWindow.Text = "项目修改";
				if (projectWindow.ShowDialog().IsYes())
				{
					TreeNode projectNode = this.FindNode(project);
					if (projectNode != null)
						this.InitNodeProject(project, selectedNode);
				}
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("操作失败！");
			}
		}

		/// <summary>
		/// 修改安置人员
		/// </summary>		
		private void MenuItemAlterPerson_Click(object sender, EventArgs e)
		{
			try
			{
				TreeNode selectedNode = (TreeNode)((ToolStripMenuItem)sender).Owner.Tag;
				Placement p = (Placement)selectedNode.Tag;
				PlacementWindow place = new PlacementWindow(Session, p);
				place.Text = "修改安置情况";
				place.ShowDialog();
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Show("操作失败！");
			}

		}

		/// <summary>
		/// 修改安置房分配
		/// </summary>		
		private void MenuItemAlterRelocateesHouse_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.RelocateesWindow == null)
					return;
				Relocatees_HouseList list = this.RelocateesWindow.GetRelocateesHouseList();
				if (list == null)
					return;
				list.GetEditButton().PerformClick();
			} catch (Exception ex)
			{
				Log.Error(ex);
				Debug.WriteLine(ex);
			}
		}


		#endregion

		/// <summary>
		/// 根据安置户的安置状态修改背景色和图标
		/// </summary>		
		private void setRelocatImageKey(TreeNode node, Relocatee relcoatee)
		{
			try
			{
				int status = relcoatee.status;
				node.ImageKey = (status == 1) ? "Relocatees1" : (status == 2) ? "Relocatees2" : "Relocatees";
				if (status == 0)
					node.BackColor = Color.LightSteelBlue;
				if (status == 1)
					node.BackColor = Color.NavajoWhite;
				if (status == 2)
					node.BackColor = SystemColors.Window;
				if (relcoatee.IsNotCompleted)
					node.ForeColor = Color.Red;

			} catch (Exception e)
			{
				Log.Error(e.Message);
			}

		}

		private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
				ToolStripMenuItem item = sender as ToolStripMenuItem;
				if (item != null && item.Owner != null)
				{
					TreeNode node = item.Owner.Tag as TreeNode;
					Relocatee relocatees = node.Tag as Relocatee;
					if (relocatees == null)
					{
						MyMessagebox.Show("没有拆迁户信息！");
						return;
					}
					relocatees_view relocatee_view = this.Session.DataModel.relocatees_view.Where(it => it.relocatees_id == relocatees.relocatees_id).FirstOrDefault();
					Relocation.UI.Xls.RelocateToExcel.RelocateeToExcel(relocatees, relocatee_view);

				}
			} catch (Exception ex)
			{
				Log.Error(ex);
				MyMessagebox.Error("操作失败！");
			}
		}

		private void 导出ToolStripMenuItem1_Click(object sender, EventArgs e)
		{
			try
			{
				TreeNode selectedNode = (TreeNode)((ToolStripMenuItem)sender).Owner.Tag;
				List<TreeNode> nodeList = new List<TreeNode>();
				if (selectedNode != null && selectedNode.Level != 0)
				{
					if (selectedNode.Level.Equals(1))
					{
						foreach (TreeNode node1 in selectedNode.Nodes)
						{
							foreach (TreeNode node2 in node1.Nodes)
							{
								if (node2 != null && node2.Tag is Relocatee)
									nodeList.Add(node2);
							}
						}
					} else if (selectedNode.Level.Equals(2))
					{
						foreach (TreeNode node1 in selectedNode.Nodes)
						{
							if (node1 != null && node1.Tag is Relocatee)
								nodeList.Add(node1);
						}
					}

				}
				tempFunction(nodeList);
			} catch (Exception ex)
			{
				Log.Error(ex);
				MyMessagebox.Error("操作失败！");
			}


		}

		private void tempFunction(List<TreeNode> nodes)
		{
			try
			{
				if (nodes.Count < 1)
					return;
				FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
				folderBrowserDialog1.Description = "请选择保存Excel的文件夹";
				folderBrowserDialog1.ShowNewFolderButton = true;
				folderBrowserDialog1.RootFolder = Environment.SpecialFolder.CommonDesktopDirectory;
				DialogResult result = folderBrowserDialog1.ShowDialog();
				if (result != DialogResult.OK)
					return;
				string folderName = folderBrowserDialog1.SelectedPath;
				if (string.IsNullOrEmpty(folderName))
					return;
				if (!Directory.Exists(folderName))
					Directory.CreateDirectory(folderName);
				foreach (TreeNode node in nodes)
				{
					if (nodes == null)
						continue;
					Relocatee relocatees = node.Tag as Relocatee;
					if (relocatees == null)
						continue;
					string r_name = Relocation.UI.Xls.RelocateToExcel.GetRelocationFileName(relocatees);
					string full_name = folderName + "\\" + r_name + ".xls";
					relocatees_view relocatee_view = this.Session.DataModel.relocatees_view.Where(it => it.relocatees_id == relocatees.relocatees_id).FirstOrDefault();
					Relocation.UI.Xls.RelocateToExcel.RelocateeToExcel(relocatees, relocatee_view, full_name, false);
				}
				if (Directory.Exists(folderName))
					System.Diagnostics.Process.Start(folderName);

			} catch (Exception ex)
			{
				Log.Error(ex);
			}
		}

		private void treeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
		{
			if (this.RelocateesWindow != null
				&& this.RelocateesWindow.IsNoSaved
				&& !MyMessagebox.Confirm("数据尚未保存，确定要离开吗？").IsYes())
				e.Cancel = true;
		}

		private void treeView_MouseClick(object sender, MouseEventArgs e)
		{
			try
			{
				if (e.Button.Equals(MouseButtons.Right))
				{
					TreeNode node = this.treeView.GetNodeAt(e.Location);
					if (node.ContextMenuStrip != null)
						node.ContextMenuStrip.Tag = node;
					this.treeView.SelectedNode = node;
				}
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}

		}
	}
}
